package controller

import (
	"fmt"
	"gitee.com/kisgod/Lamborighi/Server/app/common"
	"gitee.com/kisgod/Lamborighi/Server/app/model"
	"github.com/gin-gonic/gin"
	"strconv"
)

type ProjectController struct {
	Controller
}

func (pc *ProjectController) Add(c *gin.Context) {
	var project model.Project
	if err := c.ShouldBindJSON(&project); err != nil {
		pc.ParamError(c)
		return
	}
	pc.saveProject(c, &project)
	return
}

func (pc *ProjectController) Update(c *gin.Context) {
	id := c.Param("id")
	projectId, err := strconv.Atoi(id)
	if err != nil {
		fmt.Println(err)
		pc.ParamError(c)
		return
	}

	var project model.Project
	if err := c.ShouldBindJSON(&project); err != nil {
		pc.ParamError(c)
		return
	}

	project.ProjectId = projectId

	pc.saveProject(c, &project)
}

func (pc *ProjectController) GetProjects(c *gin.Context) {
	projects := model.GetProjects()
	//var resProjects []struct {
	//	ProjectId int
	//	Name      string
	//	Desc      string
	//	Ctime     string
	//}
	//
	//for project := range projects {
	//	resProjects = append(resProjects, struct{}{})
	//}

	pc.response(c, Response{
		Status: ResSuccess,
		Data:   projects,
	})
}

func (pc *ProjectController) saveProject(c *gin.Context, project *model.Project) {
	id, err := model.SaveProject(project)
	if err != nil {
		pc.response(c, Response{
			Status:    ResServerError,
			ErrorCode: common.Error,
			Error:     "保存项目错误"})
	} else {
		pc.response(c, Response{
			Status: ResSaved,
			Data:   struct{ Id int }{id}})
	}
	return
}
